<template>
  <view class="container">
    <!-- 文件选择器组件 -->
    <uni-file-picker
      v-model="selectedImages"
      fileMediatype="image"
      mode="grid"
      limit="1"
      @change="onImageChange"
    >
      <view class="picker-text">选择图片</view>
    </uni-file-picker>
    <!-- 上传按钮 -->
    <button @click="uploadImages" :disabled="!selectedImages.length">上传图片</button>
    <!-- 显示上传结果 -->
    <view v-if="uploadResult" class="result-text">{{ uploadResult }}</view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      // 存储用户选择的图片信息
      selectedImages: [],
      // 存储上传结果信息
      uploadResult: '',
      // 服务器的上传接口地址，需替换为实际地址
      uploadUrl: 'https://your-server-url.com/upload'
    };
  },
  methods: {
    // 处理图片选择变化的方法
    onImageChange(e) {
		console.log("获得图片",e);
      this.selectedImages = e.detail.files;
    },
    // 上传图片的方法
    uploadImages() {
		console.log("上传图片");
      if (this.selectedImages.length === 0) {
        this.uploadResult = '请先选择图片';
        return;
      }
      const image = this.selectedImages[0];
      uni.uploadFile({
        url: this.uploadUrl,
        filePath: image.path,
        name: 'image',
        // 上传成功的回调函数
        success: (res) => {
          if (res.statusCode === 200) {
            this.uploadResult = '图片上传成功';
            console.log('上传成功:', res.data);
          } else {
            this.uploadResult = '图片上传失败';
            console.error('上传失败:', res);
          }
        },
        // 上传失败的回调函数
        fail: (err) => {
          this.uploadResult = '图片上传失败';
          console.error('上传出错:', err);
        }
      });
    }
  }
};
</script>
<style scoped>
.container {
  padding: 20px;
  text-align: center;
}

.picker-text {
  padding: 10px;
  border: 1px dashed #ccc;
  border-radius: 5px;
  cursor: pointer;
}

button {
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.result-text {
  margin-top: 20px;
  color: red;
}
</style>